package com.bjbn.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ配置类
 * 
 * @author bjbn
 */
@Configuration
public class RabbitmqConfig {

    @Value("${rabbitmq.queue.name}")
    private String queueName;

    @Value("${rabbitmq.exchange.name}")
    private String exchangeName;

    @Value("${rabbitmq.exchange.type}")
    private String exchangeType;

    /**
     * 创建队列
     */
    @Bean
    public Queue radarDataQueue() {
        // 持久化队列，非排他，非自动删除
        return new Queue(queueName, true, false, false);
    }

    /**
     * 创建交换机
     */
    @Bean
    public Exchange radarDataExchange() {
        // 持久化交换机，非自动删除
        return ExchangeBuilder.fanoutExchange(exchangeName).durable(true).autoDelete().build();
    }

    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding binding(Queue radarDataQueue, Exchange radarDataExchange) {
        // Fanout交换机不需要路由键
        return BindingBuilder.bind(radarDataQueue).to(radarDataExchange).with("").noargs();
    }

    /**
     * 消息转换器
     */
    @Bean
    public Jackson2JsonMessageConverter jackson2JsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * RabbitTemplate配置
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(jackson2JsonMessageConverter());
        // 设置确认回调
        template.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                // 消息成功到达交换机
            } else {
                // 消息未到达交换机
            }
        });
        // 设置返回回调
        template.setReturnsCallback(returnedMessage -> {
            // 消息到达交换机但未路由到队列
        });
        return template;
    }

    /**
     * 监听器容器工厂
     */
    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(jackson2JsonMessageConverter());
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        factory.setConcurrentConsumers(1);
        factory.setMaxConcurrentConsumers(5);
        factory.setDefaultRequeueRejected(false);
        return factory;
    }
}